package com.mentalhealthplatform.studentV3.repository;

import com.mentalhealthplatform.appModels.Test;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Pear
 */
@Repository
public interface TestRepositoryV3 extends JpaRepository<Test, Integer> {
    @Query(value = """
    SELECT t.*
    FROM test t
    LEFT JOIN test_types tt ON t.id = tt.test_id
    WHERE (:type IS NULL OR tt.type = :type)
    GROUP BY t.id
    ORDER BY RAND()
    LIMIT :count
""", nativeQuery = true)
    List<Test> findRandomTests(@Param("count") int count, @Param("type") Integer type);

    @Modifying
    @Transactional
    @Query(value = "UPDATE test SET status = :status WHERE id IN (:testId)", nativeQuery = true)
    void updateStatusInBatch(@Param("testId") List<Integer> testId, @Param("status") Integer status);
}
